package com.qqt.csr.im.service;

import com.qqt.csr.common.utils.JsonUtil;
import com.qqt.csr.im.entity.mq.MqMessage;
import com.qqt.csr.im.entity.msg.Message;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;


/**
 * 消息事件生产者
 */
@Slf4j
@Service
public class EventMsgProducerService {
    /**
     * 事件转发 topic统一格式
     */
    public static final String EVENT_FORWARD_TOPIC = "event_forward_topic";
    /**
     * 事件转发 topic统一格式
     */
    public static final String EVENT_FORWARD_TOPIC_FORMAT = EVENT_FORWARD_TOPIC + ":%s";
    /**
     * 第三方回调 topic统一格式
     */
    public static final String MSG_CALLBACK_TOPIC = "msg_callback_to_third_topic";

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    /**
     * 发送事件消息到mq
     *
     * @param event
     * @param msgBody 传输数据 json格式
     */
    public void sendEventMsg(String event, MqMessage msgBody) {
        String topic = getEventForwardTopic(event);
        SendResult sendResult = rocketMQTemplate.syncSend(topic, MessageBuilder.withPayload(msgBody.toString()).build());
        log.info("【sendEventMsg】sendResult={}", JsonUtil.toJson(sendResult));
    }

    /**
     * 发送事件消息到mq
     *
     * @param message
     */
    public void sendCallbackMsg(Message message) {
        SendResult sendResult = rocketMQTemplate.syncSend(MSG_CALLBACK_TOPIC, MessageBuilder.withPayload(JsonUtil.toJson(message)).build());
        log.info("【sendCallbackMsg】sendResult={}", JsonUtil.toJson(sendResult));
    }

    /**
     * 获取事件转发topic
     *
     * @param event {@link String} 事件 见{@link com.qqt.csr.im.socketio.constants.EventsConstants}
     * @return {@link String} 事件转发topic
     */
    private String getEventForwardTopic(String event) {
        return String.format(EVENT_FORWARD_TOPIC_FORMAT, event);
    }
}
